import {Component, OnInit} from '@angular/core';
import {OrderService} from './order.service';
import {Authenticate} from '../../core/authenticate.service';
import {Observable} from 'rxjs';
import {InfiniteLoaderComponent} from 'ngx-weui';
import {tap} from 'rxjs/operators';

@Component({
  selector: 'app-order',
  templateUrl: './order.component.html',
  styleUrls: ['./order.component.scss']
})
export class OrderComponent implements OnInit {

  pageModels: Array<Observable<any>> = [];

  search: {
    type: number,
    page: number,
    totalPages: number,
    openId?: string,
    tradeId?: string,
    itemTitle?: string, status?: boolean,
    tkStatus?: number
  } = {type: 1, page: 0, totalPages: 0};

  constructor(private auth: Authenticate,
              private service: OrderService) {
  }

  ngOnInit() {
    this.search.openId = this.auth.authenticator.info.openId;
    this.loadPageModel();
  }

  onSearch(event: any) {
    if (!isNaN(event)) {
      this.search.tradeId = event;
    } else {
      this.search.itemTitle = event;
    }
    this.loadPageModel();
  }

  onSelect(type: number) {
    this.search.type = type;
    this.loadPageModel();
  }

  onLoadMore(comp: InfiniteLoaderComponent) {
    this.search.page++;
    if (this.search.page < this.search.totalPages) {
      const o = this.service.search(this.search).pipe(tap(() => comp.resolveLoading()));
      this.pageModels.push(o);
    } else {
      comp.setFinished();
    }

  }

  loadPageModel() {
    if (this.search.status) {
      this.search.tkStatus = 3;
    } else {
      delete this.search.tkStatus;
    }
    this.pageModels = [];
    this.pageModels.push(this.service.search(this.search).pipe(tap(model => this.search.totalPages = model.page.totalPages)));
  }

  onClear() {
    this.search.page = 0;
    delete this.search.tradeId;
    delete this.search.itemTitle;
  }
}
